;$(function($) {

	var isApp=ifApp();
	var userId = zcGetLocationParm('suid');//获得登录信息
	var uTel='';
	var serveUrl=zcUrl();


	var initFn = function() {
		bindEvt();
		headShow();
		getLogin();
		getMygifts();
		getUserVisit();
	};

	var bindEvt = function() {
		$('.turn_close').on('tap',function() {
			$(this).parents('.first_par').removeClass('show_out');
			$('.masker').removeClass('show_out');
		});

		$('.rule_btn').on('tap',function() {
			$('.masker,.gift_rule_wp').addClass('show_out');
		});

		$('.gift_btn').on('tap',function() {
			getMygifts('tapBtn');
			// 
		});

		$('#tel_num').on('keyup change', onTelNumChange);
		$('#tel_num').on('blur', onTelNumBlur);
		$('.submit_btn').on('tap',onSubmitBtnTap);
	};

	var onTelNumChange = function() { //电话号码输入控制,在blur事件里控制如果小于11位数字的情况
		var matchR = false;
		this.value=this.value.replace(/\D/g,'');
		if(this.value.length>=11) {
			matchR = /^1[34578]\d{9}$/.test(this.value);
			if(!matchR) {
				this.value='';
			}
		}
	};

	var onTelNumBlur = function() {
		if(this.value.length<11) {
			this.value='';
		}
	};

	var onSubmitBtnTap = function() {
		var tel=$('#tel_num').val();
		var linkman = $('#contact_person').val();
		var address = $('#post_address').val();
		if(!tel||!linkman||!address) {
			return;
		}else {
			submitPageInfo(tel,linkman,address);
		}

	};

	var submitPageInfo = function(tel,linkman,address) {
		var url=serveUrl+'/act3-api/submit-info';
		var data={mobile:tel,linkman:linkman,address:address,uid:userId};
		$.ajax({
			type:'POST',
			url:url,
			data:data,
			dataType:'json',
			success:function(bk) {
				//只有bk.code==0才认为提交成功
				console.log(bk);
				if(bk.code!=0) {
					//提交失败
					$('.sub_title').html('提交失败');
					$('.r_tips').html('我们稍后联系您').css({'width':'100%','text-align': 'center','padding':'0'});
				}
				$('.dialog_wp>div').removeClass('show_out');
				$('.sub_result').addClass('show_out');
				$('.txt').val('');//将表单元素置空
			},
			error:function(xhr) {
				console.log(xhr);
				console.log('ajax error');
			}
		})
	};

	var zcKl=new KinerLottery({
		rotateNum:10,
		body: "#zcTurnplate", //大转盘整体的选择符或zepto对象
        direction: 0, //0为顺时针转动,1为逆时针转动
        disabledHandler: function(key) { //当前项目待优化TODO
        	/*
				.KinerLotteryBtn 如果有.start则表示活动已经开始
								 如果有no-start则表示活动未开始
								 如果有completed则表示活动已结束
								 否则返回illegal@zhch20171031
        	*/
            switch (key) {
                case "noStart":
                    console.log("活动尚未开始");
                    break;
                case "completed":
                    console.log("活动已结束");
                    break;
                case "illegal":
                	console.log('illegal');
                	break;
            }
        }, //禁止抽奖时回调
        clickCallback: function() {
            var self = this;
        	if(!userId) {
        		window.location.href = 'http://'+psptUrl()+'/?backUrl='+encodeURIComponent(window.location.href);
        		return;
        	}
            //此处访问接口获取奖品
            $.ajax({
            	type:'POST',
            	url:serveUrl+'/act3-api/go',
            	data:{uid:userId,mobile:uTel},
            	dataType:'json',
            	success:function(bk) {
            		console.log(bk);

            		/********上线前删除 iphone8中奖专用**********/
            			// console.log('123');
            			// self.defNum = (5)*360;
            			// self.goKinerLottery( 360-(30) );
            			// return;
            		/********上线前删除 iphone8中奖专用**********/

            		if(bk.code==-2) {//当天已经抽奖一次
            			// alert('今天已经抽奖了');
            			$('.get_gift_wp')
			        		.find('.curr_tip').removeClass('show_out')
			        		.end()
			        		.find('.curr_gift img').attr('src','./img/price_coupon.png')
			        		.end()
			        		.find('.curr_gift').append('<p class="no_chance">今日已抽奖</p><p class="very_sorry">每天抽一次</p>')
			        		.end()
			        		.find('.thanks_tip').addClass('show_out').html('<li>今天的抽奖机会用完啦！</li><li>明天再来吧～</li>')
			        		.end()
			        		.addClass('show_out');
			        	$('.masker').addClass('show_out');
            			return;
            		}else if(bk.code==0) {
            			self.defNum = (bk.data.circle)*360;
            			self.goKinerLottery( 360-(bk.data.angle) );
            			
            		}else {
            			console.log(bk.code+':eror');
            		}
            		
            	},
            	error:function(xhr) {
            		console.log('ajax eroor');
            		console.log(xhr);
            	}
            })
        }, //点击抽奖按钮,再次回调中实现访问后台获取抽奖结果,拿到抽奖结果后显示抽奖画面
        KinerLotteryHandler: function(deg) {
        	$('.masker').addClass('show_out');
        	whichAward(deg);
            // console.log("恭喜您获得:" + whichAward(deg));
        } //抽奖结束回调
	});

	var whichAward = function(deg) {
		console.log(deg);
	  	if ((deg > 330 && deg <= 360) || (deg > 0 && deg <= 30)) { //iphone8
	  		$('.iphone8_wp').addClass('show_out');
        	return "iphone8";
        } else if ((deg > 30 && deg <= 90)) { //
        	getAward(200);
            return "200";
        } else if (deg > 90 && deg <= 150) { //
        	getAward(15);
            return "15";
        } else if (deg > 150 && deg <= 210) { //

        	getAward(100);
            return "100";
        } else if (deg > 210 && deg <= 270) { //
        	getAward(30);
            return "30";
        } else if (deg > 270 && deg <= 330) { //
        	$('.get_gift_wp')
        		.find('.curr_tip').removeClass('show_out')
        		.end()
        		.find('.curr_gift img').attr('src','./img/remind_thanks.png')
        		.end()
        		.find('.thanks_tip').addClass('show_out')
        		.end()
        		.addClass('show_out');
            return "谢谢参与";
        }
	}

	var headShow = function() {
		if(isApp) {
			$('#pt_wp .goback,#pt_wp .theme_share').addClass('show_out');
			// $(document).on('scroll',onWinScroll);
			$('.goback').on('click',function() {
				applyAppDetailGoback();
			});
			$('.theme_share').on('click',function() {
				// applyAppShare(obj);
				var shareObj={};
				shareObj['shareImgUrl']  = $('.plate_wp img').attr('src'); // 分享图片 默认取第一张图
				shareObj['shareUrl'   ]  = window.location.href+"&tgshare=true"; //分享url
				shareObj['shareTitle' ]  = '错峰遇见“礼” 幸运大转盘';
				shareObj['shareContent'] = '错峰遇见“礼” 幸运大转盘';    
				applyAppShare(   JSON.stringify(shareObj)  );
			});
		}else {
			$('#pt_wp .goback,#pt_wp .theme_share').remove();
		}
	};	


	function getAward(num) {//操作dom，把.thanks_tip(谢谢参与)的.show_out去掉，给.curr_tip(一种优惠券)添加.show_out，同时修改价格显示和图片路径
		$('.get_gift_wp')
			.find('#gift_price').html(num)
			.end()
			.find('.curr_tip').addClass('show_out')
			.end()
			.find('.thanks_tip').removeClass('show_out')
			.end()
			.find('.curr_gift img').attr('src','./img/'+num+'coupon.png')
			.end()
			.addClass('show_out');
	}

	function getLogin() {
		$.ajax({
			url: 'http://'+psptUrl()+'/user/get-user-info',
			type: 'POST',
			dataType: 'json',
	        xhrFields: {// 允许携带证书
	             withCredentials: true
	        },
	        crossDomain: true,// 允许跨域
			success:function(bk) {
				console.log(bk);
				var data=bk.data;
				if(bk.code==0) {
					userId=data.uid;
					uTel=data.mobile;
				}else {
					userId=undefined;
				}
			},
			error:function(xhr) {
				console.log('ajax error',xhr)
			}
		})
	}

	function getMygifts(ifTap) { //我的奖品列表
		var url=serveUrl+'/act3-api/myaward-list';
		$.ajax({
			type:'POST',
			url:url,
			data:{uid:userId},
			success:function(bk) {
				console.log(JSON.parse(bk));
				var data=JSON.parse(bk);//直接返回了数组，未做其它字段处理
				var arr=[];
			    if(data.length==0) { //暂未中奖,列表为空
					$('#all_coupons').html('暂未获奖哦，记得每天来抽奖！').css('text-align','center');
					
				}else { //有中间记录
					$.each(data,function(i,obj) {
						arr.push(
							'<li class="evy_gift clearfix">',
								'<div class="left_date">'+obj.date+'</div>',
								'<div class="gift_detail">'+obj.award_info+'</div>',
							'</li>'
						)
					});
					$('#all_coupons').html(arr.join(''));
				}
				if(ifTap==='tapBtn') { //如果点击了我的奖品按钮，则将奖品列表弹窗显示出来
					if(data.code==-8||data.msg=="用户未登录") {
						window.location.href='http://'+psptUrl()+'/?backUrl='+encodeURIComponent(window.location.href);
        				return;
					}
					$('.masker,.my_coupons').addClass('show_out');
				}
			},
			error:function(xhr) {

			}

		})
	}

	function ifApp () {
		var nu = navigator.userAgent;
		var boole=nu.indexOf('tgljAppShow')>0;
		return boole;
	}

	function zcGetLocationParm(argu_name,curr_str) { //获取url参数argu_name的值,如果未获取到则返回空,原生JS完成,不依赖$,获取不到时返回空串''
		var i=0;
		var url = curr_str||window.location.href;
		var arguStr = url.split('?')[1];
		var key_val_s = [];
		var len = 0;
		var result='';
		if(arguStr) {
			key_val_s = arguStr.split('&');
			len = key_val_s.length;
			for(i=0;i<len;i++) {
				if(argu_name==key_val_s[i].split('=')[0]) {
					result=key_val_s[i].split('=')[1];
					break;
				}
			}
		}
		return result? result=='null'?'':result :'';
	}

	function psptUrl() {
		var obj={
			'activitytest.tgljweb.com' : 'passporttest.tgljweb.com',
			'activitypre.tgljweb.com'  : 'passportpre.tgljweb.com',
			'activity.tgljweb.com'	   : 'passport.tgljweb.com',
		},
		head=window.location.hostname;
		return obj[head];
	}

	function zcUrl() {
		var head=window.location.hostname;
		var url='http://'+head;
		return url;
		// return 'http://activitytest.tgljweb.com';   //测试
		// return 'http://activitypre.tgljweb.com';    //预发布
		// return 'http://activity.tgljweb.com';       //正式
	}

	function getUserVisit() {
		var url= zcUrl()+'/act3-api/record-pv';
		$.ajax({
			type:'POST',
			url:url,
			success:function(bk) {
				console.log(bk);
			}
		})

	}

	initFn();
});